package com.sptus.web.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sptus.common.constant.CommonConstant;
import com.sptus.common.core.controller.BaseController;
import com.sptus.common.core.domain.AjaxResult;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.system.utils.GmailSendVerificationCode;
import com.sptus.common.utils.JwtUtil;
import com.sptus.common.utils.ip.IpUtils;
import com.sptus.common.utils.oConvertUtils;
import com.sptus.framework.annotation.AutoLog;
import com.sptus.framework.query.QueryGenerator;
import com.sptus.system.domain.Equipment;
import com.sptus.web.config.DataLoaderConfig;
import com.sptus.web.entity.SptUser;
import com.sptus.web.entity.SptUserAddress;
import com.sptus.web.entity.SptUserEquipment;
import com.sptus.web.entity.SptUserParent;
import com.sptus.web.model.SysLoginModel;
import com.sptus.web.service.*;
import com.sptus.web.util.CryptUtil;
import com.sptus.web.util.DySmsLimit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Api(tags="app普通用户")
@RestController
@RequestMapping("/SptUser/sptUser")
@Slf4j
public class SptUserController extends BaseController {
   @Autowired
   private ISptUserService sptUserService;
    @Autowired
    private RedisCache redisUtil;

    @Autowired
    private CloudIEquipmentService equipmentService;

    @Autowired
    ISptUserParentService sptUserParentService;

    @Autowired
    ISptUserEquipmentService sptUserEquipmentService;

    @Autowired
    ISptUserAddressService sptUserAddressService;


    public  static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    @ApiOperation("邮箱发送修改密码验证码")
    @RequestMapping(value = "/sendPasswordEmail", method = RequestMethod.POST)
    public AjaxResult sendPasswordEmail(@RequestBody SptUser user, HttpServletRequest request) {
        String clientIp = IpUtils.getIpAddr(request);

        String redisKey = CommonConstant.EMAIL_PASSWORD_KEY_PRE+user.getEmail();
        if(!DySmsLimit.canSendSms(clientIp)){
            log.warn("--------[警告] IP地址:{}, 短信接口请求太多-------", clientIp);
            return AjaxResult.error(CommonConstant.PHONE_SMS_FAIL_CODE, "短信接口请求太多，请稍后再试！");
        }
        if(StringUtils.isEmpty(user.getEmail())){
            return AjaxResult.error("邮箱不能为空");
        }
        String captcha = RandomUtil.randomNumbers(6);
        redisUtil.setCacheObject(redisKey, captcha, 600, TimeUnit.SECONDS);


        String to = user.getEmail(); // 收件人邮箱
        String from = DataLoaderConfig.getGlobalData().get("spt.auth.code.email") ; // 发件人邮箱（你的Gmail）
        String host = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.host") ; // SMTP服务器地址
        String port =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.post"); // Gmail SMTP端口
        // 生成验证码（这里仅为示例）
        String verificationCode = captcha;
        // Gmail用户名和密码（或使用应用专用密码）
        String username =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.username");
        String password = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.pass");
        try {
            cachedThreadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    GmailSendVerificationCode.sendEmailWithVerificationCode(to, verificationCode, from, host, port, username, password,clientIp);
                }
            }));
        }catch (Exception e){
            //自定义异常
            return AjaxResult.error("unsent messages");

        }finally {

        }
        return AjaxResult.success("Message sent successfully");

    }
    @ApiOperation("邮箱发送注册验证码")
    @RequestMapping(value = "/sendEmail", method = RequestMethod.POST)
    public AjaxResult sendEmail(@RequestBody SptUser user, HttpServletRequest request) {
        String clientIp = IpUtils.getIpAddr(request);

        String redisKey = CommonConstant.EMAIL_KEY_PRE+user.getEmail();
        if(!DySmsLimit.canSendSms(clientIp)){
            log.warn("--------[警告] IP地址:{}, 短信接口请求太多-------", clientIp);
            return AjaxResult.error(CommonConstant.PHONE_SMS_FAIL_CODE, "短信接口请求太多，请稍后再试！");
        }
        if(StringUtils.isEmpty(user.getEmail())){
            return AjaxResult.error("The mailbox cannot be empty");
        }
        String captcha = RandomUtil.randomNumbers(6);
        redisUtil.setCacheObject(redisKey, captcha, 600,TimeUnit.SECONDS);

        System.out.println( DataLoaderConfig.getGlobalData());
        String to = user.getEmail(); // 收件人邮箱
        String from = DataLoaderConfig.getGlobalData().get("spt.auth.code.email") ; // 发件人邮箱（你的Gmail）
        String host = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.host") ; // SMTP服务器地址
        String port =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.post"); // Gmail SMTP端口
        // 生成验证码（这里仅为示例）
        String verificationCode = captcha;
        // Gmail用户名和密码（或使用应用专用密码）
        String username =  DataLoaderConfig.getGlobalData().get("spt.auth.code.email.username");
        String password = DataLoaderConfig.getGlobalData().get("spt.auth.code.email.pass");
        try {
            cachedThreadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    GmailSendVerificationCode.sendEmailWithVerificationCode(to, verificationCode, from, host, port, username, password,clientIp);
                }
            }));
        }catch (Exception e){
            //自定义异常
            return AjaxResult.error("unsent messages");
        }finally {

        }
        return AjaxResult.success("Message sent successfully");

    }

    @ApiOperation("邮箱注册接口")
    @RequestMapping(value = "/gmailSign", method = RequestMethod.POST)
    public AjaxResult gmailSign(@RequestBody SptUser user, HttpServletRequest request) {
        String confirmPassword = user.getConfirmPassword();
        String smscode = user.getSmscode();

        if(oConvertUtils.isNotEmpty(user.getEmail())){
            LambdaQueryWrapper<SptUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SptUser::getEmail,user.getEmail());

            SptUser one = sptUserService.getOne(queryWrapper);
            //密码校验
            if(!user.getPassword().equals(confirmPassword) ){
                return AjaxResult.error("Different password");
            }
            if(user.getPassword().length()<6){
                return AjaxResult.error("The password does not comply with the length rule");
            }
            //校验验证码是否正确
            if(redisUtil.getCacheObject(CommonConstant.EMAIL_KEY_PRE+user.getEmail())==null){
                return AjaxResult.error("Please enter the verification code");
            }
            if(!redisUtil.getCacheObject(CommonConstant.EMAIL_KEY_PRE+user.getEmail()).equals(smscode)){
                return AjaxResult.error("Verification code error");
            }
            redisUtil.deleteObject(CommonConstant.EMAIL_KEY_PRE+user.getEmail());

            //校验用户是否存在
            if (one != null) {
                return AjaxResult.error("he mailbox has been registered");
            }
        }
        String password = user.getPassword();
        user.setPassword(CryptUtil.encodedPassword(password));
        user.setCreatedAt(new Date());
        user.setUpdatedAt(new Date());
        sptUserService.save(user);

        // step.2 校验用户是否存在且有效
//		LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
////		queryWrapper.eq(SysUser::getUsername, username);
//		SysUser sysUser = sysUserService.getOne(queryWrapper);
//		result = sysUserService.checkUserIsEffective(sysUser);
//		if (!result.isSuccess()) {
//			return result;
//		}
        return AjaxResult.success("registered successfully");
    }

    public static void main(String[] args) {
        String s = CryptUtil.encodedPassword(String.valueOf(123456));
        System.out.println(s);
    }



    @ApiOperation("邮箱登录接口")
    @RequestMapping(value = "/gmailLogin", method = RequestMethod.POST)
    public AjaxResult gmailLogin(@RequestBody SysLoginModel sysLoginModel, HttpServletRequest request) {
        String username = sysLoginModel.getUsername();
        String password = sysLoginModel.getPassword();
        if(isLoginFailOvertimes(username)){
            return AjaxResult.error("This user has failed to log in too many times, please log in again after 10 minutes!");
        }
        String s = CryptUtil.encodedPassword(password);
        LambdaQueryWrapper<SptUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SptUser::getEmail, username);
        SptUser one = sptUserService.getOne(queryWrapper);
        if(one ==null){
            return AjaxResult.error("The user does not exist.");
        }
        if(!CryptUtil.checkTruePassword(password,one.getPassword())){
            return AjaxResult.error("wrong password");
        }
        String token = JwtUtil.sign(username, password);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        one.setPassword("");
        jsonObject.put("userinfo",one);
        //设置 token
        redisUtil.setCacheObject(CommonConstant.PREFIX_EMAIL_USER_TOKEN+token,one);

        //获取用户数据设备数据
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSignBy,one.getId());
        List<Equipment> equipmentlist = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);
        jsonObject.put("equipmentExist",equipmentlist.size()>0);
        List<Equipment> collect = equipmentlist.stream().filter(e -> !e.getStatus().equals("2")).collect(Collectors.toList());
        jsonObject.put("networkExist",collect.size()>0);
        jsonObject.put("updateUser", !ObjectUtil.isEmpty(one.getUpdatedAt()));
        return AjaxResult.success("login successfully", jsonObject);
    }
    @ApiOperation("忘记密码接口")
    @RequestMapping(value = "/forgetPassword", method = RequestMethod.POST)
    public AjaxResult forgetPassword(@RequestBody SptUser user, HttpServletRequest request) {
        String confirmPassword = user.getConfirmPassword();
        String smscode = user.getSmscode();
        if(oConvertUtils.isNotEmpty(user.getEmail())){
            LambdaQueryWrapper<SptUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SptUser::getEmail,user.getEmail());

            SptUser one = sptUserService.getOne(queryWrapper);
            //密码校验
            if(!user.getPassword().equals(confirmPassword) ){
                return AjaxResult.error("Different password");
            }
            if(user.getPassword().length()<6){
                return AjaxResult.error("The password does not comply with the length rule");
            }
            //校验验证码是否正确
            if(redisUtil.getCacheObject(CommonConstant.EMAIL_PASSWORD_KEY_PRE+user.getEmail())==null){
                return AjaxResult.error("Please enter the verification code");
            }
            if(!redisUtil.getCacheObject(CommonConstant.EMAIL_PASSWORD_KEY_PRE+user.getEmail()).equals(smscode)){
                return AjaxResult.error("Verification code error");
            }
            redisUtil.deleteObject(CommonConstant.EMAIL_PASSWORD_KEY_PRE+user.getEmail());
            //修改密码
            LambdaQueryWrapper<SptUser> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(SptUser::getEmail,one.getEmail());
            one.setPassword(CryptUtil.encodedPassword(user.getPassword()));
            sptUserService.update(one,lambdaQueryWrapper);

        }


        // step.2 校验用户是否存在且有效
//		LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
////		queryWrapper.eq(SysUser::getUsername, username);
//		SysUser sysUser = sysUserService.getOne(queryWrapper);
//		result = sysUserService.checkUserIsEffective(sysUser);
//		if (!result.isSuccess()) {
//			return result;
//		}
        return AjaxResult.success("operate successfully");
    }

    private boolean isLoginFailOvertimes(String username){
        String key = CommonConstant.LOGIN_FAIL + username;
        Object failTime = redisUtil.getCacheObject(key);
        if(failTime!=null){
            Integer val = Integer.parseInt(failTime.toString());
            if(val>5){
                return true;
            }
        }
        return false;
    }

   /**
    * 分页列表查询
    *
    * @param sptUser
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   //@AutoLog(value = "spt_user-分页列表查询")
   @ApiOperation(value="spt_user-分页列表查询", notes="spt_user-分页列表查询")
   @GetMapping(value = "/listInfo")
   public AjaxResult queryPageList(SptUser sptUser,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       QueryWrapper<SptUser> queryWrapper = QueryGenerator.initQueryWrapper(sptUser, req.getParameterMap());
       Page<SptUser> page = new Page<SptUser>(pageNo, pageSize);
       IPage<SptUser> pageList = sptUserService.page(page, queryWrapper);
       return AjaxResult.success(pageList);
   }
    @ApiOperation(value="spt_user-分页列表查询", notes="spt_user-分页列表查询")
    @GetMapping(value = "/list")
    public AjaxResult queryUserPageList(SptUser sptUser,
                                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                @RequestParam(name="searckKey", defaultValue="") String searckKey,
                                                HttpServletRequest req) {
        QueryWrapper<SptUser> lambdaQueryWrapper =new QueryWrapper<>();

        lambdaQueryWrapper.isNull("spt_user.deleted_at")
                        .and(w->w.like("spt_user.nickname",searckKey)
                                .or()
                                .like("spt_user.last_name",searckKey)
                                .or()
                                .like("spt_user.first_name",searckKey)
                                .or()
                                .like("spt_user.email",searckKey));
        Page<SptUser> page = new Page<SptUser>(pageNo, pageSize);
        IPage<HashMap<String,Object>> pageList = sptUserService.getUserListPage(page, lambdaQueryWrapper);
        return AjaxResult.success(pageList);
    }

//	 @ApiOperation()
   @ApiOperation(value="spt_user-分页列表查询", notes="spt_user-分页列表查询")
   @GetMapping(value = "/getUserClass")
   public AjaxResult getUserClass() {
   ArrayList<HashMap<String,Object>>	arrayList=	sptUserService.getUserClass();
   return AjaxResult.success(arrayList);
}

   /**
    *   添加
    *
    * @param sptUser
    * @return
    */
   @AutoLog(value = "spt_user-添加")
   @ApiOperation(value="spt_user-添加", notes="spt_user-添加")
//   @RequiresPermissions("SptUser:spt_user:add")
   @PostMapping(value = "/add")
   public AjaxResult add(@RequestBody SptUser sptUser ) {
       sptUser.setCreatedAt(new Date());
       sptUser.setGoogleUuid(System.currentTimeMillis()+"");
       sptUser.setIsGoogleAuth(1);
       if(com.sptus.common.utils.StringUtils.isEmpty(sptUser.getPassword())){
           sptUser.setPassword("123456");
       }
       sptUser.setPassword(CryptUtil.encodedPassword(sptUser.getPassword()));
       SptUser sptUserInfo = sptUserService.saveSptUser(sptUser);
       HashMap<String, Object> stringStringHashMap = new HashMap<>();
       stringStringHashMap.put("sptUser", sptUser);
       return AjaxResult.success(stringStringHashMap);
   }

    @PostMapping("updatePassword")
    public AjaxResult updatePassword(@RequestBody SptUser sptUser) {
        sptUser.setPassword(CryptUtil.encodedPassword(sptUser.getPassword()));
        sptUserService.updateById(sptUser);
        return AjaxResult.success("return boolean!");
    };
   /**
    *  编辑
    *
    *
    */
   @AutoLog(value = "spt_user-编辑")
   @ApiOperation(value="spt_user-编辑", notes="spt_user-编辑")
//   @RequiresPermissions("SptUser:spt_user:edit")
   @Transactional
   @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
   public AjaxResult edit(@RequestBody SptUser one) {
       sptUserService.updateById(one);
       SptUserAddress sptUserAddress = new SptUserAddress();
       sptUserAddress.setUserId(one.getId()+"");
       sptUserAddress.setCity(one.getCity());
       sptUserAddress.setCountry(one.getCountry());
       sptUserAddress.setPhone(one.getPhone());
       sptUserAddress.setAddress(one.getAddress());
       sptUserAddress.setFirstName(one.getFirstName());
       sptUserAddress.setLastName(one.getLastName());
       sptUserAddress.setZipcode(one.getZipCode());
       sptUserAddress.setState(one.getState());
       LambdaQueryWrapper<SptUserAddress> sptUserAddressLambdaQueryWrapper = new LambdaQueryWrapper<>();
       sptUserAddressLambdaQueryWrapper.eq(SptUserAddress::getUserId, one.getId());
       SptUserAddress sptUserAddressOne = sptUserAddressService.getOne(sptUserAddressLambdaQueryWrapper);
       if(ObjectUtil.isEmpty(sptUserAddressOne)){
           sptUserAddress.setUserId(one.getId()+"");
           sptUserAddressService.save(sptUserAddress);
       }else {
           sptUserAddressService.update(sptUserAddress,sptUserAddressLambdaQueryWrapper);
       }

       return AjaxResult.success("return boolean!");
   }

    @AutoLog(value = "spt_user-编辑")
    @ApiOperation(value="spt_user-编辑", notes="spt_user-编辑")
    @RequestMapping(value = "/editUser", method = {RequestMethod.PUT, RequestMethod.POST})
    public AjaxResult editUser(@RequestBody SptUser sptUser) {
        sptUserService.updateById(sptUser);
        return AjaxResult.success("return boolean!");
    }

//	 @AutoLog(value = "spt_user-通过id删除")
    @ApiOperation(value="spt_user-通过id删除", notes="spt_user-通过id删除")
    @PostMapping(value = "/deleteUser")
    public AjaxResult deleteUser(@RequestBody SptUser sptUser) {
        sptUserService.removeUserById(sptUser.getId()+"");
//		 sptUserService.removeById(id);
        return AjaxResult.success("删除成功!");
    }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
//	@AutoLog(value = "spt_user-通过id删除")
//	@ApiOperation(value="spt_user-通过id删除", notes="spt_user-通过id删除")
//	@RequiresPermissions("SptUser:spt_user:delete")
//	@DeleteMapping(value = "/delete")
//	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
//		sptUserService.removeById(id);
//		return Result.OK("删除成功!");
//	}

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "spt_user-批量删除")
   @ApiOperation(value="spt_user-批量删除", notes="spt_user-批量删除")
//   @RequiresPermissions("SptUser:spt_user:deleteBatch")
   @DeleteMapping(value = "/deleteBatch")
   public AjaxResult deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.sptUserService.removeByIds(Arrays.asList(ids.split(",")));
       return AjaxResult.success("Batch deletion succeeded!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "spt_user-通过id查询")
   @ApiOperation(value="spt_user-通过id查询", notes="spt_user-通过id查询")
   @GetMapping(value = "/queryById")
   public AjaxResult queryById(@RequestParam(name="id",required=true) String id) {
       SptUser sptUser = sptUserService.getById(id);
       if(sptUser==null) {
           return AjaxResult.error("No corresponding data found");
       }
       return AjaxResult.success(sptUser);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param sptUser
   */
//   @RequiresPermissions("SptUser:spt_user:exportXls")
//   @RequestMapping(value = "/exportXls")
//   public ModelAndView exportXls(HttpServletRequest request, SptUser sptUser) {
//       return super.exportXls(request, sptUser, SptUser.class, "spt_user");
//   }

   /**
    * * 通过excel导入数据
   *
   * @param
   * @param
   * @return
   */
//   @RequiresPermissions("SptUser:spt_user:importExcel")
//   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//       return super.importExcel(request, response, SptUser.class);
//   }



    @RequestMapping(value = "/getUserDevList", method = RequestMethod.GET)
    public AjaxResult getUserDevList(SptUser sptUser) {
        return selectModelEquipmentRealize(sptUser);
    }


    public AjaxResult selectModelEquipmentRealize( SptUser sptUser) {

        ArrayList<String> ids = new ArrayList<>();
        LambdaQueryWrapper<SptUserParent> sptUserParentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getUserId,sptUser.getId());
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getState,"1");
        List<HashMap<String,String>> sptUserParents = sptUserParentService.selectListInfo(sptUserParentLambdaQueryWrapper);
        if(sptUserParents.size()>0){
            ids.add(sptUserParents.get(0).get("parent_id"));
        }
        ids.add(sptUser.getId()+"");

        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.in(SptUserEquipment::getUserId,ids);

        List<SptUserEquipment> sptUserEquipments = sptUserEquipmentService.getBaseMapper().selectList(sptUserEquipmentLambdaQueryWrapper);
        ArrayList<Equipment> equipmentlist = new ArrayList<>();
        List<String> collect = sptUserEquipments.stream().map(e -> e.getEquipmentId()).collect(Collectors.toList());
        if(  collect.size()==0){
            return AjaxResult.success("Query success", equipmentlist);
        }
        QueryWrapper<Equipment> equipmentQueryWrapper = new QueryWrapper<>();
        equipmentQueryWrapper.in("equipment.sn",collect);
        List<Equipment>  equipmentList=  equipmentService.selectListInfo(equipmentQueryWrapper);
        Map<String, Equipment> collectMap = equipmentList.stream().collect(Collectors.toMap(Equipment::getSn, Function.identity(), (value1, value2) -> value1));
        for (SptUserEquipment sptUserEquipment : sptUserEquipments) {
            Equipment equipmentObj  = collectMap.get(sptUserEquipment.getEquipmentId());

            if(!StringUtils.isEmpty(equipmentObj)){
                equipmentObj.setName(sptUserEquipment.getDevName());
                equipmentlist.add(equipmentObj);
            }

        }
        equipmentlist.stream().filter(e-> e.getStatus().equals("1")
        ).forEach(e->{

        });
        return AjaxResult.success("Query success", equipmentlist);
    }


    @PreAuthorize("@ss.hasPermi('SptUser:device:update')")
    @ApiOperation(value="equipment-添加", notes="equipment-添加")
    @PostMapping(value = "/addDevice")
    public AjaxResult addDevice(@RequestBody Equipment equipment) {
        Integer id = equipment.getUserId();
        equipment.setSignBy(id+"");
        equipment.setStatus("2");
        if (StringUtils.isEmpty(equipment)){
            equipment.setName(equipment.getSn());
        }
        LambdaQueryWrapper<Equipment> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(Equipment::getSn,equipment.getSn());
        List<Equipment> equipment1 = equipmentService.getBaseMapper().selectList(objectLambdaQueryWrapper);
        if (equipment1.size()>0){
            LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,equipment1.get(0).getSn());
            sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getUserId,equipment.getUserId());
            SptUserEquipment sptUserEquipmentObj = sptUserEquipmentService.getBaseMapper().selectOne(sptUserEquipmentLambdaQueryWrapper);
            if(!ObjectUtils.isEmpty(sptUserEquipmentObj)){
                return AjaxResult.success("successfully added！");
            }
        }else {
            equipmentService.save(equipment);
        }
        SptUserEquipment sptUserEquipment = new SptUserEquipment();
        sptUserEquipment.setEquipmentId(equipment.getSn());
        sptUserEquipment.setUserId(equipment.getUserId()+"");
        sptUserEquipment.setDevName(equipment.getName());
        sptUserEquipmentService.save(sptUserEquipment);

        return AjaxResult.success("successfully added！");
    }
    //    @AutoLog(value = "设备编辑")

    @PreAuthorize("@ss.hasPermi('SptUser:device:update')")
    @ApiOperation(value="设备编辑", notes="设备编辑")
    @PostMapping(value = "/updateDevice")
    public AjaxResult updateDevice(@RequestBody Equipment equipment) {
        Integer id = equipment.getUserId();
        equipment.setSignBy(id+"");
        equipment.setStatus(equipment.getStatus());
        LambdaQueryWrapper<SptUserParent> sptUserParentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getUserId,equipment.getUserId());
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getState,"1");
        List<HashMap<String,String>> sptUserParents = sptUserParentService.selectListInfo(sptUserParentLambdaQueryWrapper);
        ArrayList<String> ids = new ArrayList<>();
        if(sptUserParents.size()>0){
            ids.add(sptUserParents.get(0).get("parent_id"));
        }
        ids.add(id+"");
        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,equipment.getSn());
        sptUserEquipmentLambdaQueryWrapper.in(SptUserEquipment::getUserId,ids);
        SptUserEquipment sptUserEquipment = sptUserEquipmentService.getBaseMapper().selectOne(sptUserEquipmentLambdaQueryWrapper);
        LambdaQueryWrapper<Equipment> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(Equipment::getSn,equipment.getSn());
        if (sptUserEquipment!=null){
            equipmentService.update(equipment,objectLambdaQueryWrapper);
            sptUserEquipment.setDevName(equipment.getName());
            sptUserEquipmentService.update(sptUserEquipment,sptUserEquipmentLambdaQueryWrapper);
            return  AjaxResult.success("modify successfully");
        }

        return AjaxResult.success("Device does not exist！");
    }
    @PreAuthorize("@ss.hasPermi('SptUser:spt_user:delete')")
    @ApiOperation(value="设备-通过id删除", notes="设备-通过id删除")
    @PostMapping(value = "/deviceDelete")
    public AjaxResult delete(@RequestBody SptUser sptUser) {

        LambdaQueryWrapper<Equipment> lambdaQueryWrapper = new LambdaQueryWrapper<Equipment>();
        lambdaQueryWrapper.eq(Equipment::getSn,sptUser.getSn());
        Equipment equipment = equipmentService.getBaseMapper().selectOne(lambdaQueryWrapper);
        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,equipment.getSn());
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getUserId,sptUser.getId());
        sptUserEquipmentService.getBaseMapper().delete(sptUserEquipmentLambdaQueryWrapper);
        if (equipment.getStatus().equals("2")){
            equipmentService.getBaseMapper().delete(lambdaQueryWrapper);
        }
        return AjaxResult.success("successfully delete!");
    }
}
